﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using CarbonExchange.Bll;

namespace CarbonExchange.WebControls
{
    public abstract class AuditQuestionSigleItemBase : AuditQuestionBase
    {
        public override int GetActiveItemsCount()
        {
            return 1;
        }
        public override int RenderItems(int start, int end, HtmlTextWriter writer)
        {
            this.Render(writer);
            return 1;
        }
    }

    public abstract class AuditQuestionBase : UserControl
    {

        public void SetContext(QuestionTextConfiguration questionTextConfiguration, int siteId, Audit audit)
        {
            _Configuration = questionTextConfiguration;
            _QuestionId = questionTextConfiguration.QuestionId;
            _QuestionType = questionTextConfiguration.QuestionType;
            _SiteId = siteId;
            _Audit = audit;
            _AuditId = audit.Id;
        }


        private QuestionTextConfiguration.QuestionTypes _QuestionType;
        private int _QuestionId { get; set; }
        private int _SiteId { get; set; }
        private QuestionTextConfiguration _Configuration;
        protected QuestionTextConfiguration Configuration
        {
            get
            {
                if (_Configuration == null && _QuestionType != QuestionTextConfiguration.QuestionTypes.Unknown)
                {
                    _Configuration = new QuestionTextConfiguration(_QuestionType, _QuestionId, _SiteId);
                }
                return _Configuration;
            }
        }

        private int _AuditId;
        private Audit _Audit;
        protected Audit Audit
        {
            get
            {
                if (_Audit == null && _AuditId > 0)
                {
                    var factory = new AuditFactory();
                    _Audit = factory.GetById(_AuditId);
                }
                return _Audit;
            }
        }

        protected string GetChoiceDisplayText(string choice)
        {
            string[] items = choice.Split(' ');
            return items.Select(x => string.Concat(x.Substring(0, 1).ToUpper(), x.Substring(1))).ToFormatedStringWithSpacer(" ", x => x);
        }


        protected string GetText(string name)
        {
            string retVal = null;
            if (Configuration != null)
            {
                var tmp = Configuration.TextValues.Where(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();
                if (tmp != null)
                {
                    retVal = tmp.GetText();
                }
            }
            return retVal;
        }

        private CarbonExchange.Bll.Answer _Answer;
        protected CarbonExchange.Bll.Answer Answer
        {
            get
            {
                if (_Answer == null)
                {
                    AnswerFactory factory = new AnswerFactory();
                    _Answer = factory.GetByAuditIdAndQuestionId(_AuditId, _QuestionId);
                    _Answer = _Answer ?? new CarbonExchange.Bll.Answer(_AuditId, _QuestionId);
                }
                return _Answer;
            }
        }



        protected override object SaveViewState()
        {
            ViewState["AuditId"] = _AuditId;
            ViewState["QuestionType"] = _QuestionType;
            ViewState["QuestionId"] = _QuestionId;
            ViewState["SiteId"] = _SiteId;
            return base.SaveViewState();
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            _AuditId = (int)ViewState["AuditId"];
            _QuestionType = (QuestionTextConfiguration.QuestionTypes)ViewState["QuestionType"];
            _QuestionId = (int)ViewState["QuestionId"];
            _SiteId = (int)ViewState["SiteId"];
        }

        public virtual bool Save()
        {
            CarbonExchange.Bll.AnswerFactory answerFactory = new CarbonExchange.Bll.AnswerFactory();
            var completed = SaveQuestion();
            answerFactory.Save(Answer);
            return completed;
        }

        /// <summary>
        /// Save the question
        /// </summary>
        /// <returns>bool values to indercate whether question is completed</returns>
        protected abstract bool SaveQuestion();


        protected CarbonExchange.Bll.AmeeProfileItem EnsureProfileItem(string answerItemName, CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory, string dataPath, string dataChoices)
        {
            var tmpAnswerItem = Answer.GetItemByName(answerItemName);

            var dataItem = dataCategoryFactory.GetByPath(dataPath, dataChoices);

            if (dataItem == null || !dataItem.DataItemSelected)
            {
                throw new ApplicationException(string.Format("Could not find dataitem at '{0}' with choices '{1}'", dataItem.Path, dataItem.SelectedAsString()));
            }

            CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = null;
            if (tmpAnswerItem != null && !string.IsNullOrEmpty(tmpAnswerItem.AmeeId))
            {
                tmpProfileItem = profileItemFactory.GetByPath(Audit.AuditKey, tmpAnswerItem.Path, tmpAnswerItem.AmeeId);
            }
            if (tmpProfileItem == null || tmpProfileItem.DataItemId != dataItem.Id)
            {
                tmpProfileItem = profileItemFactory.CreateItem(dataItem, Audit.AuditKey, DateTime.Now.ToString("f"), Audit.StartDate);
            }
            return tmpProfileItem;
        }

        protected CarbonExchange.Bll.AmeeProfileItem EnsureProfileItem(string answerItemName, CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, CarbonExchange.Bll.AmeeDataCatagory dataCategory)
        {
            var tmpAnswerItem = Answer.GetItemByName(answerItemName);
            CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = null;
            if (tmpAnswerItem != null && !string.IsNullOrEmpty(tmpAnswerItem.AmeeId))
            {
                tmpProfileItem = profileItemFactory.GetByPath(Audit.AuditKey, tmpAnswerItem.Path, tmpAnswerItem.AmeeId);
            }

            if (tmpProfileItem == null || tmpProfileItem.DataItemId != dataCategory.Id)
            {
                tmpProfileItem = profileItemFactory.CreateItem(dataCategory, Audit.AuditKey, DateTime.Now.ToString("f"), Audit.StartDate);
            }

            return tmpProfileItem;
        }

        public abstract int GetActiveItemsCount();

        internal int RenderItems(int p, int p_2)
        {
            throw new NotImplementedException();
        }

        public abstract int RenderItems(int start, int end, HtmlTextWriter writer);
        /*public virtual int RenderItems(int start, int end, HtmlTextWriter writer)
        {
            writer.Write(string.Format("Items {0} To {1}", start, end));
            return end - start;
        }*/
    }

}
